package week07.necessary.batchinsert;

import lombok.extern.slf4j.Slf4j;
import week07.necessary.batchinsert.base.AbstractBatchInsertImpl;
import week07.necessary.batchinsert.entities.Orders;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 预处理SQL形式批量插入
 */
@Slf4j
public class PreparedStatementInsert extends AbstractBatchInsertImpl {

    public PreparedStatementInsert(int total, int partition) {
        super(total, partition);
    }

    @Override
    public void test() throws SQLException {
        Connection connection = getConnection();
        String sql = "INSERT INTO week07.orders(user_id, trade_no, total_fee, trade_fee) VALUES (?,?,?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        final AtomicLong atomicLong = new AtomicLong();
        super.batchInsert(listCollection -> {
            for (List<Orders> ordersList : listCollection) {
                for (Orders orders : ordersList) {
                    try {
                        preparedStatement.setInt(1, orders.getUserId());
                        preparedStatement.setString(2, orders.getTradeNo());
                        preparedStatement.setInt(3, orders.getTotalFee());
                        preparedStatement.setInt(4, orders.getTradeFee());
                        preparedStatement.addBatch();
                    } catch (SQLException e) {
                        throw new RuntimeException(e);
                    }
                }
                try {
                    long start = System.currentTimeMillis();
                    preparedStatement.executeBatch();
                    atomicLong.addAndGet(System.currentTimeMillis() - start);
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        log.info("[批量插入]耗时{}毫秒", atomicLong.get());
        preparedStatement.close();
    }
}
